package org.bmi.gwt.examples.clienttr.client;

import org.bmi.gwt.examples.clienttr.shared.Element1Proxy;
import org.bmi.gwt.examples.clienttr.shared.Element2Proxy;
import org.bmi.gwt.mi.client.channel.Connection;
import org.bmi.gwt.mi.client.events.ConnectionHandler;
import org.bmi.gwt.mi.shared.BroadChannel;
import org.bmi.gwt.mi.shared.Channel;
import org.bmi.gwt.mi.shared.MiTransaction;
import org.bmi.gwt.mi.shared.callbacks.BindCallback;
import org.bmi.gwt.mi.shared.exceptions.InvalidArgumentException;
import org.bmi.gwt.mi.shared.exceptions.MiException;
import org.bmi.gwt.mi.shared.exceptions.NameParseException;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;

public class ClientTransaction implements EntryPoint
{
	@Override
	public void onModuleLoad()
	{
		Connection.createConnection(new ConnectionHandler()
		{
			@Override
			public void onException(Exception e)
			{
				GWT.log("an error occurred: ", e);
			}

			@Override
			public void onConnectionBegin(Connection connection)
			{
				try
				{
					Channel qListen = connection.getChannel("org.bmi.gwt.mi.test.ClientTransaction");
					BroadChannel qSend = connection.getChannel("org.bmi.gwt.mi.test.ClientTransaction");

					/* A transaction is created... */

					final MiTransaction t = qSend.createTransaction();

					qListen.bind(new BindCallback()
					{
						@Override
						public void onError(MiException error)
						{
							GWT.log("An error occurred: " + error);
						}

						@Override
						public void onBound(Channel channel)
						{
							try
							{
								Element1Proxy proxy1 = t.proxyToNewObject(Element1Proxy.class);
								Element1Proxy proxy2 = t.proxyToNewObject(Element1Proxy.class, "String from client");

								Element2Proxy proxy3 = t.proxyToNewObject(Element2Proxy.class, proxy1.getCopy());
								Element2Proxy proxy4 = t.proxyToNewObject(Element2Proxy.class, proxy2);

								proxy3.getElement().print();
								proxy4.getElement().print();
							}
							catch (InvalidArgumentException e)
							{
								e.printStackTrace();
							}

							t.commit();
						}
					});
				}
				catch (NameParseException e)
				{
					e.printStackTrace();
				}
			}
		});
	}
}
